package com.ztc.ZtcWallet.service;

import com.aqgj.shiro.ShiroDbRealm;
import com.ztc.AppUser.dao.AppUserDao;
import com.ztc.ZtcOrder.bean.ZtcOrder;
import com.ztc.ZtcWallet.bean.ZtcWallet;
import com.ztc.ZtcWalletLog.bean.ZtcWalletLog;
import com.ztc.ZtcWalletLog.dao.ZtcWalletLogDao;
import com.ztc.util.enums.WalletLogType;
import com.ztc.util.exceptions.BusinessException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ztc.ZtcWallet.dao.ZtcWalletDao;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("ZtcWallet")
public class ZtcWalletManager{

    @Autowired
    private ZtcWalletDao ztcWalletDao;
    @Autowired
    private ZtcWalletLogDao ztcWalletLogDao;
    @Autowired
    private AppUserDao appUserDao;

    private final Logger LOGGER = LogManager.getLogger(ShiroDbRealm.class);

    public String save(ZtcWallet ztcWallet){
    	ztcWalletDao.save(ztcWallet);
        return ztcWallet.getId();
    }

	public void update(ZtcWallet ztcWallet) {
		ztcWalletDao.update(ztcWallet);
	}

    public ZtcWallet findUserWallet(String businessId){
        return ztcWalletDao.findUniqueBy("fkUserId",businessId);
    }

    /**
     * 退票扣除三级返利
     *
     * @param ztcOrder 订单信息
     * @param isWallet 是否为余额支付
     * @param refundFee 退款金额
     * @param isRefundPenaltyFee 是否为退违约金
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveThreeRebateLogAndUpdateWalletByRefund(ZtcOrder ztcOrder, Boolean isWallet, BigDecimal refundFee,boolean isRefundPenaltyFee) {
        //获取一级用户钱包信息
        ZtcWallet ztcWallet = ztcWalletDao.get(ztcOrder.getFkZtcWalletId()==null?"":ztcOrder.getFkZtcWalletId());
        if(isRefundPenaltyFee){
            if(isWallet){
                //返还用户退票违约金返还
                BigDecimal afterBalance = ztcWallet.getMoney().add(refundFee);
                ztcWallet.setMoney(afterBalance);
                ztcWallet.setTmoney(ztcWallet.getTmoney().add(refundFee));
                ztcWalletDao.update(ztcWallet);
                //保存一级用户退票违约金返还日志
                saveWalletLog(ztcWallet.getFkUserId(), ztcOrder.getId(), refundFee, afterBalance, 9);
            }
            return;
        }
        BigDecimal payFee = ztcOrder.getPayBalance();
        if (isWallet) {
            //返还用户退票金额
            BigDecimal afterBalance = ztcWallet.getMoney().add(payFee);
            ztcWallet.setMoney(afterBalance);
            ztcWallet.setTmoney(ztcWallet.getTmoney().add(payFee));
            ztcWalletDao.update(ztcWallet);
            //保存一级用户退票交易记录日志
            saveWalletLog(ztcWallet.getFkUserId(), ztcOrder.getId(), payFee, afterBalance, 2);
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new BusinessException("处理失败，请重试!");
        }
        if(ztcOrder.getOrderType() == 2 || ztcOrder.getOrderType() == 4){
            return;
        }
        if (refundFee.compareTo(payFee) == -1 && isWallet) {
            BigDecimal money = payFee.subtract(refundFee);
            if(money.compareTo(BigDecimal.ZERO)>0){
                //保存用户一级返利退票违约金日志
                BigDecimal afterBalance = ztcWallet.getMoney().subtract(money);
                ztcWallet.setMoney(afterBalance);
                ztcWallet.setTmoney(ztcWallet.getTmoney().subtract(money));
                ztcWalletDao.update(ztcWallet);
                saveWalletLog(ztcWallet.getFkUserId(),ztcOrder.getId(), money.negate(), afterBalance, 8);
            }
        }
        Set<Integer> integerSet = new HashSet<>(3);
        integerSet.add(5);
        integerSet.add(6);
        integerSet.add(7);
        List<ZtcWalletLog> ztcWalletLogList = ztcWalletLogDao.getWalletLogByOrderIdAndType(ztcOrder.getId(),integerSet);
        if(ztcWalletLogList == null || ztcWalletLogList.size() == 0){
            return;
        }
        for(ZtcWalletLog ztcWalletLog:ztcWalletLogList){
            switch (ztcWalletLog.getType()){
                case 5:
                    //返还用户一级返利退票资金
                    BigDecimal afterBalance = ztcWallet.getMoney().subtract(ztcWalletLog.getMoney());
                    ztcWallet.setMoney(afterBalance);
                    ztcWalletDao.update(ztcWallet);
                    //保存用户一级返利退票交易记录日志
                    saveWalletLog(ztcWalletLog.getFkUserId(), ztcWalletLog.getFkOrderId(), ztcWalletLog.getMoney().negate(), afterBalance, 10);
                    break;
                case 6:
                    ztcWallet = ztcWalletDao.findUniqueBy("fkUserId",ztcWalletLog.getFkUserId());
                    //返还用户二级返利退票资金
                    afterBalance = ztcWallet.getMoney().subtract(ztcWalletLog.getMoney());
                    ztcWallet.setMoney(afterBalance);
                    ztcWalletDao.update(ztcWallet);
                    //保存用户二级返利退票交易记录日志
                    saveWalletLog(ztcWalletLog.getFkUserId(), ztcWalletLog.getFkOrderId(), ztcWalletLog.getMoney().negate(), afterBalance, 11);
                    break;
                case 7:
                    ztcWallet = ztcWalletDao.findUniqueBy("fkUserId",ztcWalletLog.getFkUserId());
                    //返还用户三级返利退票资金
                    afterBalance = ztcWallet.getMoney().subtract(ztcWalletLog.getMoney());
                    ztcWallet.setMoney(afterBalance);
                    ztcWalletDao.update(ztcWallet);
                    //保存用户三级返利交易记录日志
                    saveWalletLog(ztcWalletLog.getFkUserId(), ztcWalletLog.getFkOrderId(), ztcWalletLog.getMoney().negate(), afterBalance, 12);
                    break;
                default:
                    break;
            }
        }
    }


    /**
     * 保存资金日志信息
     *
     * @param userId       用户ID
     * @param orderNumber  商户订单号
     * @param money        金额
     * @param afterBalance 本次交易后余额
     * @param type         类型:1-购票;2-退票;3-充值;4-提现;5-一级返利收入;6-二级返利收入;7-三级返利收入;8-退票违约金;9-退票违约金返还;10-一级返利退票支出;11-二级返利退票支出;12-三级返利退票支出;13:提现失败入账;14-顺风车收入;15-顺风车退票支出;16-快递费支出;17-快递退款收入;18-快递费收入;19-代收货款入账
     */
    public void saveWalletLog(String userId, String orderNumber, BigDecimal money, BigDecimal afterBalance, int type) {
        ZtcWalletLog ztcWalletLog = new ZtcWalletLog();
        ztcWalletLog.setFkUserId(userId);
        ztcWalletLog.setAddTime(System.currentTimeMillis());
        ztcWalletLog.setComment(WalletLogType.getName(type));
        ztcWalletLog.setFkOrderId(orderNumber);
        //订单金额
        ztcWalletLog.setMoney(money);
        ztcWalletLog.setAfterBalance(afterBalance);
        ztcWalletLog.setType(type);
        ztcWalletLogDao.save(ztcWalletLog);
    }

    /**
     * 根据用户ID获取钱包信息
     * @param userId
     * @return
     */
    public ZtcWallet getWalletByUserId(String userId){
        List<ZtcWallet> walletList = ztcWalletDao.findBy("fkUserId",userId);
        if(walletList==null || walletList.size()<=0){
            return null;
        }
        return walletList.get(0);
    }
}
